package com.loto.webapp.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.apache.struts2.ServletActionContext;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.loto.webapp.model.TopMenu;
import com.loto.webapp.util.Constants;
import com.loto.webapp.util.Files;

public class AuthorizationFilter extends HttpServlet implements Filter {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static HttpServletRequest request;
	private static HttpServletResponse response;

	@Override
	public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
			FilterChain filterChain) throws IOException, ServletException {
		request = (HttpServletRequest) sRequest;
		response = (HttpServletResponse) sResponse;
		HttpSession session = request.getSession();
		String url = request.getServletPath();
		String contextPath = request.getContextPath();
		if (url.equals(""))
			url += "/";
		if (url.startsWith("/") && !url.startsWith("/login")
				&& !url.startsWith("/ajax")
				&& !url.startsWith("/generateValidateCode")) {
			String username = (String) session
					.getAttribute(Constants.USERNAME_KEY);
			if (null == username || username.equals("")) {
				response.sendRedirect(contextPath + "/login.jsp");
				return;
			} else if (!url.startsWith("/ctrl") && !url.startsWith("/index")
					&& !verifyAccess(username, url)) {
				response.sendRedirect(contextPath + "/login.jsp");
				return;
			}
		}
		filterChain.doFilter(sRequest, sResponse);
	}

	private boolean verifyAccess(String username, String pageUrl) {
		boolean isAccess = false;
		if (pageUrl.equals("/logout.do"))
			isAccess = true;
		else {
			Document document = Files.getMenuXml(request, username);
			org.w3c.dom.Element rootElement = document.getDocumentElement();
			NodeList list = rootElement.getElementsByTagName("ChildMenu");

			Document relatedDocument = Files.getRelatedXml(request);
			org.w3c.dom.Element relateRootElement = relatedDocument
					.getDocumentElement();
			NodeList relateList = relateRootElement
					.getElementsByTagName("Related");

			for (int i = 0; i < list.getLength(); i++) {
				org.w3c.dom.Element element = (org.w3c.dom.Element) list
						.item(i);
				if (element.getAttribute("Url").equals(pageUrl)) {
					isAccess = true;
					break;
				} else {
					for (int j = 0; j < relateList.getLength(); j++) {
						org.w3c.dom.Element ele = (org.w3c.dom.Element) relateList
								.item(j);
						if (ele.getAttribute("Url").equals(
								element.getAttribute("Url"))) {
							NodeList sublist = ele
									.getElementsByTagName("ChildRelated");
							for (int k = 0; k < sublist.getLength(); k++) {
								org.w3c.dom.Element subEle = (org.w3c.dom.Element) sublist
										.item(k);
								if (subEle.getAttribute("Url").equals(pageUrl)) {
									isAccess = true;
									break;
								}
							}
							if (isAccess)
								break;
						}
					}
				}
			}
		}
		return isAccess;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
